<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display: flex">
        <div>
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <transition name="from"></transition>
              <span v-show="!showCardNav">
                <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
              </span>
              <transition name="to"></transition>
              <span v-show="showCardNav">
                <i style="margin-right: 5px" class="el-icon-arrow-up"></i>
              </span>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <span style="display: inline-block;margin-bottom: 10px;">
                  <span style="margin-right: 12px">特材成品名称</span>
                  <el-input v-model="tableParam.productName" style="width: 240px" clearable placeholder="请输入" @keyup.enter.native="gettableData()" />
                </span>
                <span style="margin-left: 24px">
                  <span style="margin-right: 12px">成品型号</span>
                  <el-input v-model="tableParam.productType" style="width: 240px" clearable placeholder="请输入" @keyup.enter.native="gettableData()" />
                </span>
                <span style="margin-left: 24px">
                  <span style="margin-right: 12px">状态</span>
                  <el-select v-model="tableParam.dataStatus" style="width: 120px" placeholder="请选择">
                    <el-option label="全部" :value="null"></el-option>
                    <el-option label="未完工" :value="0"></el-option>
                    <el-option label="已完工" :value="1"></el-option>
                    <el-option label="已入库" :value="2"></el-option>
                  </el-select>
                </span>
                <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
                <el-button size="medium" class="bottom_all_two" style="margin-left: 12px" @click="init()">重 置</el-button>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card_nav">
            <div>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0" @click="productList=[],addFromDate('添加')">
                <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
                添加
              </el-button>
            </div>
            <div>
              <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px">
                <el-link :underline="false">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_filtrate"></i>
                  </span>
                  筛选
                </el-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in table" :key="index">
                    <el-checkbox v-model="item.status">{{
                      item.label
                      }}</el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          <div class="card" style="padding-top:10px">
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="tableData" tooltip-effect="dark">
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :min-width="item.width" :fixed="item.label =='操作'?'right':false">
                    <template slot-scope="scope">
                      <div v-if="item.label=='备注'">
                        <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="bottom">
                          <div class="ellipsis2">{{scope.row.remark}} </div>
                        </el-tooltip>
                      </div>
                      <div v-else-if="item.label == '操作'">
                        <el-button v-if="scope.row.dataStatus > 0&&ButtonList.findIndex(res=>(res.buttonValue=='RUKU'))!==-1" class="bottom_one" size="mini" @click="open('addDialog1',scope.row)">
                          入库
                        </el-button>
                        <el-button v-if="scope.row.dataStatus == 0&&ButtonList.findIndex(res=>(res.buttonValue=='QUERENWANGONG'))!==-1" class="bottom_one" size="mini" @click="open('addDialog2',scope.row)">
                          确认完工
                        </el-button>
                      </div>
                      <div v-else-if="item.label == '状态'">
                        <span v-if="scope.row.dataStatus == 0" style="color: #969799">未完工</span>
                        <span v-else-if="scope.row.dataStatus == 1" style="color: #00a754">已完工</span>
                        <span v-else style="color: red">已入库</span>
                      </div>
                      <div v-else-if="item.label == '入库检验结果'">
                        <span v-if="scope.row.storageTest == 'NG'" style="color: red">不合格</span>
                        <span v-else-if="scope.row.storageTest == 'OK'" style="color: #00a754">合格</span>
                        <span v-else style="color: #00a754">-</span>
                      </div>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
            <div class="card_bottom">
              <div class="card_bottom_left">
                <div class="top_page_totle">总共{{ total }}条</div>
                <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" layout="prev, pager, next, jumper" :total="total" @current-change="gettableData()"></el-pagination>
              </div>
              <div>
                <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="480px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div class="dialoginfo">
        <el-form ref="reffromDate" :rules="rules" :inline="true" :model="fromDate" label-width="110px">
          <el-form-item prop="companyId" :rules="[{required: true,message: '请选择所属单位',trigger: 'change',}]">
            <span slot="label" style="color: #ff0000">所属单位</span>
            <el-select ref="company" v-model="fromDate.companyId" placeholder="请选择" @change="$nextTick(()=>{fromDate.company = $refs.company.selectedLabel}),productListFun(fromDate.companyId)">
              <el-option v-for="(item,index) in companyList" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="productId">
            <span slot="label" style="color: #ff0000">特材成品</span>
            <el-select v-model="fromDate.productId" placeholder="请选择" filterable>
              <el-option v-for="(item, index) in productList" :key="index" :label="item.productName+'-'+item.type" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="production">
            <span slot="label" style="color: #ff0000">生产罐次</span>
            <el-input v-model="fromDate.productions" placeholder="请输入" type="Number" clearable @change="changeValue">
              <template slot="append">罐次</template>
            </el-input>
          </el-form-item>
          <el-form-item prop="production">
            <span slot="label" style="color: #ff0000">生产量</span>
            <el-input v-model="fromDate.production" disabled placeholder="请输入" type="Number" clearable>
            </el-input>
          </el-form-item>
          <el-form-item prop="remark">
            <span slot="label">备注</span>
            <el-input v-model="fromDate.remark" placeholder="请填写备注" class="textarea" type="textarea" resize="none" rows="5"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="pagessubmitFromDate()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 入库 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog1" width="480px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">入库</span>
      <div>
        <div class="dialoginfotitle">生产量：{{lowData.productNum}}</div>
        <div style="padding-bottom:15px">
          <el-button size="mini" class="bottom_all" style="margin-left: 0" :disabled="tankList.length==0" @click="additem()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加
          </el-button>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="lowData.tanks" tooltip-effect="dark" :row-class-name="className">
          <el-table-column label="成品罐" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.id" placeholder="请选择" style="width:100%" @change="change(scope.row)">
                <el-option v-for="(item, index) in tankList" :key="index" :label="item.tankName" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="入库量" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.receipt" type="Number" placeholder="请输入" style="width:100%">
                <template slot="append">吨</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left">
            <template slot-scope="scope">
              <el-button size="mini" class="bottom_two" @click="delitem(scope.$index)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="reset('addDialog1')">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="submit1()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  queryPage, saveOrUpdate, productList, updateDataStatus, tankList
} from "@/api/smart/specialmaterial/prodplan.js";
import { getUserInfo } from "@/utils/auth";
import { permissionsCompanyList } from "@/api/common.js";
export default {
  mixins: [mixin],
  data() {
    return {
      companyList: [],
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      saveOrUpdate: saveOrUpdate,
      /*表格数据*/
      pagesType: 0,
      table: [
        { label: "生产计划编号", width: "160", prop: "code", status: true },
        { label: "状态", width: "120", prop: "", status: true },
        { label: "所属单位", width: "120", prop: "company", status: true },
        { label: "特材成品名称", width: "120", prop: "productName", status: true },
        { label: "成品型号", width: "120", prop: "productType", status: true },
        { label: "生产量（吨）", width: "120", prop: "production", status: true },
        { label: "备注", width: "200", prop: "remark", status: true },
        { label: "入库时间", width: "160", prop: "storageTime", status: true },
        { label: "完工时间", width: "160", prop: "completeTime", status: true },
        { label: "入库检验结果", width: "120", prop: "", status: true },
        { label: "操作", width: "200", prop: "", status: true },
      ],
      rules: {
        productId: [{ required: true, message: "请选择特材成品", trigger: "change" }],
        production: [{ required: true, message: "请输入生产量", trigger: "blur" }],
      },
      fromDate: {
        companyId: '',
        productId: '',
        production: '',
        productions: '',
        remark: '',
      },
      productList: [],
      tankList: [],
      lowData: {},
      low: {},
      addDialog1: false
    };
  },
  async created() {
    this.companyList = await permissionsCompanyList()
    this.tableParam = {
      ...this.tableParam,
      productName: "",
      productType: "",
      dataStatus: null
    };
    this.gettableData();
  },
  methods: {
    async productListFun(companyId) {
      this.fromDate.productId = ''
      const { data } = await productList({ companyId: companyId, page: 1, pageSize: 9999999, enable: 1, dataType: 2 })
      this.productList = data.data
    },
    changeValue(value) {
      this.fromDate.production = this.$regExp.FloatMul(value, 10);
    },
    change(low) {
      let item = this.tankList.find(res => (res.id == low.id))
      low.inventory = item.inventory
    },
    className({ row }) {
      if (row.status == 0) {
        return 'hidden'
      }
    },
    additem() {
      this.lowData.tanks.push({
        id: '',
        inventory: '',
        receipt: '',
      })
    },
    delitem(index) {
      this.lowData.tanks.splice(index, 1)
    },
    reset(key) {
      this[key] = false
      this.tankList = []
    },
    submit1() {
      let _this = this;
      if (_this.lowData.tanks.length == 0) {
        _this.$message({
          message: "请添加入库数据",
          type: 'warning'
        });
        return
      }
      if (_this.lowData.tanks.every(item => (item.id == '' || item.receipt == ''))) {
        _this.$message({
          message: "请填写信息完整",
          type: 'warning'
        });
        return
      }
      /**去重*/
      let hash = {};
      const deWeight = (item, cur) => {
        hash[cur.id] ? '' : hash[cur.id] = true && item.push(cur);
        return item
      }
      let arr = _this.lowData.tanks.reduce(deWeight, [])
      /**合计*/
      const sum = (prev, cur) => (prev + Number(cur.receipt))
      let num = _this.lowData.tanks.reduce(sum, 0)
      if (_this.lowData.tanks.length !== arr.length) {
        _this.$message({
          message: '不能添加重复的原料罐',
          type: 'warning'
        });
        return
      }
      if (_this.lowData.productNum !== num) {
        // _this.$message({
        //   message: '入库量之和要等于生产量',
        //   type: 'warning'
        // });
        // return
      }
      _this.lowData.storageTime = new Date().Format('yyyy-MM-dd hh:mm:ss')
      updateDataStatus(_this.lowData).then(res => {
        if (res.code == 1001) {
          _this.$message({
            message: '入库成功！',
            type: 'success'
          });
          _this.reset('addDialog1')
          _this.gettableData();
        }
      })
    },
    /*重置数据*/
    init() {
      this.tableParam.productName = "";
      this.tableParam.productType = "";
      this.tableParam.dataStatus = null;
      this.gettableData();
    },
    async open(key, low) {
      this.low = this.copy(low)
      if (key == "addDialog1") {
        this[key] = true
        const { data: list } = await tankList({ page: 1, pageSize: 9999999, productId: low.productId })
        this.tankList = list.data
        let arr = []
        if (list.data.length !== 0) {
          arr.push({
            id: '',
            inventory: '',
            receipt: '',
          })
        }
        this.lowData = {
          planId: low.id,
          planStatus: 2,
          productNum: low.production,
          tanks: arr
        }
      }
      if (key == "addDialog2") {
        this.$confirm('此操作会将确认完工, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'bottom_all_two',
          confirmButtonClass: 'bottom_all',
          type: 'warning'
        }).then(() => {
          let data = {
            planId: low.id,
            planStatus: 1,
            companyId: low.companyId,
            company: low.company,
            materialNo: low.code,
            productId: low.productId,
            productName: low.productName,
            productModel: low.productType,
            completeTime: new Date().Format('yyyy-MM-dd hh:mm:ss')
          }

          console.log(data)
          updateDataStatus(data).then(res => {
            if (res.code == 1001) {
              this.$message({
                message: "已确认完工",
                type: 'success'
              });
              this.gettableData();
            }
          })
        }).catch(() => {
        });
      }
    },
    pagessubmitFromDate() {
      let _this = this
      _this.$refs.reffromDate.validate(async (valid) => {
        if (valid) {
          let item = _this.productList.find(res => (res.id == _this.fromDate.productId))
          _this.fromDate.productName = item.productName
          _this.fromDate.productType = item.type
          getUserInfo()
          _this.submitFromDate();
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-input,
.el-select,
.el-textarea {
  width: 240px;
}
.hidden {
  display: none;
}
.dialoginfotitle {
  font-weight: bold;
  padding-bottom: 20px;
  font-size: 16px;
}
</style>